package com.fanghuaman.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fanghuaman.model.category.dto.CategoryPageDto;
import com.fanghuaman.model.category.pojo.Category;
import com.fanghuaman.model.category.vo.CategoryListAllVo;
import com.fanghuaman.model.category.vo.CategoryPageVo;
import com.fanghuaman.model.common.emus.HttpEmus;
import com.fanghuaman.model.common.vo.ResponseResult;
import com.fanghuaman.product.mapper.CategoryMapper;
import com.fanghuaman.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smh
 * @since 2024-12-08
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分页查询
     *
     * @param categoryPageDto
     * @return
     */
    @Override
    public ResponseResult list(CategoryPageDto categoryPageDto) {
        // 检查参数
        categoryPageDto.check();
        // 构造分页对象
        Page<Category> page = new Page<>(categoryPageDto.getPage(), categoryPageDto.getSize());
        // 拼接查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (categoryPageDto.getCategoryName() != null && !categoryPageDto.getCategoryName().isEmpty()) {
            wrapper.like(Category::getName, categoryPageDto.getCategoryName());
        }
        if (categoryPageDto.getLevel() != null) {
            wrapper.eq(Category::getLevel, categoryPageDto.getLevel());
        }

        //  查询数据
        page = this.page(page, wrapper);
        // 拼接返回结果
        CategoryPageVo categoryPageVo = new CategoryPageVo();
        categoryPageVo.setTotal(page.getTotal());
        categoryPageVo.setList(page.getRecords());
        categoryPageVo.setPage(categoryPageDto.getPage());
        categoryPageVo.setSize(categoryPageDto.getSize());


        return ResponseResult.success(categoryPageVo);
    }

    @Override
    public ResponseResult getByParentId(Long parentId) {
        if (parentId == null) {
            return ResponseResult.fail(HttpEmus.PARAM_ERROR);
        }
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getParentId, parentId);
        List<Category> categoryList = categoryMapper.selectList(wrapper);

        return ResponseResult.success(categoryList);
    }

    /**
     * 查询所有分类
     *
     * @return
     */
    @Override
    public ResponseResult listAll() {
        List<CategoryListAllVo> resList = categoryMapper.listAll();
        return ResponseResult.success(resList);
    }
}
